package com.wdb007.venus.svc.biz.manager;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wdb.exchange.constant.EventEnum;
import com.wdb.exchange.constant.SourceEnum;
import com.wdb.exchange.model.Event;
import com.wdb007.venus.svc.dal.user.dao.UserInfoDAO;
import com.wdb007.venus.svc.dal.user.dao.WxUserRelationDAO;
import com.wdb007.venus.svc.dal.user.model.WxUserRelationDO;

@Component("intersystemCommunicationManager")
public class IntersystemCommunicationManager {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	
	@Autowired
	private UserInfoDAO userInfoDAO;
	
	@Autowired
	private WxUserRelationDAO wxUserRelationDAO;
	
	@Autowired
	private RabbitManager rabbitManager;
	
	public void publishEvent(Long userId, EventEnum eventEnum) {
		logger.info("publishEvent===userId:[{}], event:[{}]", userId, eventEnum.name());
		String mobileNo = userInfoDAO.get(userId).getMobileNo();
		try {
			Event event = new Event();
			event.source = SourceEnum.API;
			event.userId = userId;
			event.mobile = mobileNo;
			event.eventTime = System.currentTimeMillis();
			event.event = eventEnum;
			//查询用户的appId和openI
			WxUserRelationDO query = new WxUserRelationDO();
			query.setUserId(userId);
			List<WxUserRelationDO> list = wxUserRelationDAO.listByCondition(query);
			if(!CollectionUtils.isEmpty(list)) {
				for(WxUserRelationDO relation : list) {
					event.appId = relation.getAppId();
					event.openId = relation.getOpenid();
					rabbitManager.sendToServiceExchange(event.toJson());
				}
			}else {
				rabbitManager.sendToServiceExchange(event.toJson());
			}
		}catch(Exception e) {
			logger.error("publishEvent Error", e);
		}
	}
	
	public void publishScanAndDrawCouponEvent(Long staffId, String couponRuleId, EventEnum eventAction) {
		logger.info("publishScanAndDrawCouponEvent===staffId:[{}],couponRuleId:[{}]", staffId, couponRuleId);
		try {
			Event event = new Event();
			event.source = SourceEnum.API;
			event.userId = staffId;
			event.eventTime = System.currentTimeMillis();
			event.event = eventAction;
			event.extra = couponRuleId;
			rabbitManager.sendToServiceExchange(event.toJson());
		}catch(Exception e) {
			logger.error("publishEvent Error", e);
		}
	}
}
